package com.sgb.kjwl.view.ui.fragment.home;

import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.BaseHeightViewPagerFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLogisticsAcceptForCarriageBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.sgb.kjwl.model.entity.transport.CarriageInfo;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.kjwl.view.ui.adapter.home.HomeSourceOfSupplyAdapter;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.model.entity.transport.CarHallEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.VehicleDetailActivity;
import com.sgb.kjwl.view.ui.adapter.home.SourceOfCarAdapter;
import com.sgb.kjwl.view.ui.adapter.home.SourceOfGoodsAdapter;
import com.sgb.kjwl.view.ui.adapter.home.VehicleOwner1Adapter;
import com.sgb.kjwl.view.widget.HomeGoodsSelectionTypePopWindow;
import com.sgb.kjwl.viewmodel.home.LogisticsAcceptForCarriageModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.event.EventConstant;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.view.entity.MenuEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;


/**
 * Description:
 * Author cfk
 * Time
 * 物流货运大厅中的竞价承运fragment
 * {
 * "name": "竞价承运",
 * "id": 1
 * },
 * {
 * "name": "竞价货运",
 * "id": 2
 * },
 * {
 * "name": "货车大厅",
 * "id": 3
 * },
 * {
 * "name": "货运大厅",
 * "id": 4
 * }
 */
public class LogisticsAcceptForCarriageFragment extends BaseHeightViewPagerFragment {


    @Inject
    LogisticsAcceptForCarriageModel viewModel;

    private FragmentLogisticsAcceptForCarriageBinding binding;
    private int mItemType;//0 竞价承运,1货源信息 2 货车信息,3 竞价货运
    private GoodsInfoTypeEntity3 mTypeEntity3;
    private List<GoodsInfoTypeEntity3> mTabEntityData;
    private HomeGoodsSelectionTypePopWindow mPopWindow;

    private SourceOfCarAdapter carrierAdapter;
    private HomeSourceOfSupplyAdapter sourceOfSupplyAdapter; // 货运大厅/竞价货运
    private SourceOfGoodsAdapter sourceOfGoodsAdapter; //货源信息
    private VehicleOwner1Adapter mVehicleOwnerAdapter;

    public static LogisticsAcceptForCarriageFragment newInstance(int position,BannerEntity bannerEntity,boolean isRefresh) {
        LogisticsAcceptForCarriageFragment fragment = new LogisticsAcceptForCarriageFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM, bannerEntity);
        args.putInt(ARG_PARAM_POS, position);
        args.putBoolean(ARG_isRefresh, isRefresh);
        fragment.setArguments(args);
        return fragment;
    }

    private int getItemType() {
        int mItemType = -1;
        BannerEntity bannerEntity = (BannerEntity) getArguments().getSerializable(ARG_PARAM);
        switch (bannerEntity.getName()) {
            case "司机找货":
                mItemType = 0;
                break;
            case "货源信息":
                mItemType = 1;
                break;
            case "货车信息":
                mItemType = 2;
                break;
            case "竞价货运":
                mItemType = 3;
                break;
        }
        return mItemType;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(getActivity())) {
            EventBus.getDefault().register(getActivity());
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_logistics_accept_for_carriage, container, false);
        return binding.getRoot();
    }

    @Nullable
    @Override
    public View getView() {
        return super.getView();
    }

    @Override
    protected void initView() {
        super.initView();
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
        if (mItemType == -1) {
            return;
        }
        binding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        binding.recycler.setNestedScrollingEnabled(false);
        binding.recycler.addItemDecoration(new RecyclerView.ItemDecoration(){
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.dp1);
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(getActivity(), 2);
        switch (mItemType) {
            case 0://竞价承运
                carrierAdapter = new SourceOfCarAdapter(getActivity(), null, true);
                binding.recycler.setLayoutManager(gridLayoutManager);
                binding.recycler.setAdapter(carrierAdapter);
                carrierAdapter.setOnItemClick(new AdapterOnItemClick<CarriageInfo>() {
                    @Override
                    public void onItemClick(CarriageInfo carriageInfo, int position) {
                        CarriageDetailActivity.start(getActivity(), carriageInfo.getCarrierNo(), 1);
                    }
                });
                binding.recycler.setAdapter(carrierAdapter);
                break;
            case 1://货源信息
                sourceOfGoodsAdapter = new SourceOfGoodsAdapter(getActivity(), null);
                binding.recycler.setLayoutManager(gridLayoutManager2);
                binding.recycler.setPadding(0,0, (int) getActivity().getResources().getDimension(R.dimen.dp10),0);
                sourceOfGoodsAdapter.setOnItemClick(new AdapterOnItemClick<GoodsInfoEntity>() {
                    @Override
                    public void onItemClick(GoodsInfoEntity goodsInfoEntity, int position) {
                        //viewModel.getH5Url(goodsInfoEntity.getNo(), mItemType);
                        //GoodsInfoDetailActivity3.start(getActivity(), goodsInfoEntity3.getNo() + "");
                        viewModel.goodsSourceStatusCheck(goodsInfoEntity.getNo(), goodsInfoEntity.getPattern());
                        //GeneralPrjDetailActivity.start(getActivity(), goodsInfoEntity.getNo(), position, false);

                    }
                });
                binding.recycler.setAdapter(sourceOfGoodsAdapter);
                break;
            case 3://竞价货运
                sourceOfSupplyAdapter = new HomeSourceOfSupplyAdapter(getActivity(), null);
                binding.recycler.setLayoutManager(gridLayoutManager);
                binding.recycler.setAdapter(sourceOfSupplyAdapter);
                sourceOfSupplyAdapter.setOnItemClick(new AdapterOnItemClick<GoodsInfoEntity>() {
                    @Override
                    public void onItemClick(GoodsInfoEntity goodsInfoEntity, int position) {
                        viewModel.goodsSourceStatusCheck(goodsInfoEntity.getNo(), goodsInfoEntity.getPattern());
                        //viewModel.getH5Url(goodsInfoEntity.getNo(), mItemType);
                    }
                });
                binding.recycler.setAdapter(sourceOfSupplyAdapter);
                break;
            case 2://货车信息
                mVehicleOwnerAdapter = new VehicleOwner1Adapter(getActivity(), null);
                binding.recycler.setLayoutManager(gridLayoutManager2);
                binding.recycler.setPadding(0,0, (int) getActivity().getResources().getDimension(R.dimen.dp10),0);
                mVehicleOwnerAdapter.setOnItemClick(new AdapterOnItemClick<CarHallEntity>() {
                    @Override
                    public void onItemClick(CarHallEntity carsInfoEntity3, int position) {
                        //viewModel.getH5Url(carsInfoEntity3.getNo(),mItemType);
                        //CarsInfoDetailActivity3.start(getActivity(), carsInfoEntity3.getNo() + "");
                        VehicleDetailActivity.start(getActivity(), carsInfoEntity3.getDriverAuthNo());
                    }
                });
                binding.recycler.setAdapter(mVehicleOwnerAdapter);
                break;
        }
        binding.tvMore.setOnClickListener(v -> loadData(true));
        binding.ivPopup.setOnClickListener(v -> showPopup());
        binding.tvGoModel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 6));
            }
        });
        binding.tvGoModel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 6));
            }
        });
    }
    public void IsRefresh(boolean isRefresh) {
        setIsRefresh(isRefresh);
        loadData(false);
    }
    @Override
    protected void onLazyLoad() {
        switch (mItemType) {
            case 0://竞价承运
            case 2://货车信息
                viewModel.getCarsType();
                break;
            case 1://货源信息
            case 3://竞价货运
                viewModel.getGoodsType3();
                break;
        }
    }

    @Override
    public void onVisible() {
        super.onVisible();
//        if (binding.emptyView.getVisibility() == View.VISIBLE) {
//            if (mTabEntityData == null || mTabEntityData.size() == 0) {
//                onLazyLoad();
//                return;
//            }
            loadData(false);
//        } else {
//            switch (mItemType) {
//                case 0://竞价承运
//                    loadCacheData(carrierAdapter);
//                    break;
//                case 1://货运大厅
//                case 3://竞价货运
//                    loadCacheData(sourceOfSupplyAdapter);
//                    break;
//                case 2://货车大厅
//                    loadCacheData(mVehicleOwnerAdapter);
//                    break;
//            }
//        }
    }

    private void loadData(boolean isLoadMore) {
        if (mTypeEntity3 == null)return;
        switch (mItemType) {
            case 0://竞价承运->竞价承运需求
                viewModel.getCarrierInfoList(mTypeEntity3, isLoadMore, getPosition(),mItemType,getIsRefresh());
                break;
            case 1://货源信息->货运大厅大厅
                viewModel.getNewGoodsList(mTypeEntity3, 0, isLoadMore, getPosition(),mItemType,getIsRefresh());
                //viewModel.getFilterSourceList3(mItemType, mTypeEntity3.getNo(), 0, isLoadMore, getIsRefresh());
                break;
            case 2://货车信息->车辆大厅
                viewModel.getCarList(mTypeEntity3, 0, isLoadMore, getPosition(),mItemType,getIsRefresh());
                break;
            case 3://竞价货运->竞价竞价货运
                //viewModel.getGoodsList(mTypeEntity3, 1, isLoadMore, getPosition(),mItemType,getIsRefresh());
                viewModel.getNewGoodsList(mTypeEntity3, 1, isLoadMore, getPosition(),mItemType,getIsRefresh());
                break;
        }
    }
    //展示类型数据
    public <T> void showGoodsOrCarsTypeData(List<T> list) {
        List<GoodsInfoTypeEntity3> data = (List<GoodsInfoTypeEntity3>)list;
        if (data == null || data.size() == 0) {
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.llTabLayout.setVisibility(View.INVISIBLE);
            return;
        }
        binding.llTabLayout.setVisibility(View.VISIBLE);
        mTabEntityData = data;
        mTypeEntity3 = mTabEntityData.get(0);
        //循环
        for (int i = 0; i < data.size(); i++) {
            //创建tab的item
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(data.get(i).getName()));
        }
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mTypeEntity3 = mTabEntityData.get(tab.getPosition());
                //判断弹窗是否为空
                if (mPopWindow == null) {
                    //为空时，创建弹窗
                    mPopWindow = new HomeGoodsSelectionTypePopWindow(getActivity());
                    List<MenuEntity> menuEntities = new ArrayList<>();
                    for (GoodsInfoTypeEntity3 tabEntityDatum : mTabEntityData) {
                        MenuEntity entity = new MenuEntity();
                        entity.setName(tabEntityDatum.getName());
                        entity.setId(tabEntityDatum.getNo());
                        menuEntities.add(entity);
                    }
                    //弹窗设置数据
                    mPopWindow.setData(menuEntities);
                    mPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                        @Override
                        public void result(Object key1, Object key2, Object key3) {
                            binding.ivPopup.setImageResource(R.mipmap.btn_expand2);
                            Objects.requireNonNull(binding.tabLayout.getTabAt(((int) key2))).select();
                        }
                    });
                }
                mPopWindow.setDefItem(tab.getPosition());
                loadData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        loadData(false);
    }

    public <T> void showList(List<T> list,boolean isLoadMore){
        switch (mItemType) {
            case 0://竞价承运->竞价承运需求
                updateData(carrierAdapter, (List<CarriageInfo>)list, isLoadMore, 3);
                break;
            case 1://货运大厅->货运大厅大厅
                updateData(sourceOfGoodsAdapter, (List<GoodsInfoEntity>)list, isLoadMore, 6);
                break;
            case 3://竞价货运->竞价竞价货运
                updateData(sourceOfSupplyAdapter, (List<GoodsInfoEntity>)list, isLoadMore, 3);
                break;
            case 2://货车大厅->车辆大厅
                updateData(mVehicleOwnerAdapter, (List<CarHallEntity>)list, isLoadMore, 6);
                break;
        }

    }

    //加载或更新数据
    public <T> void updateData(BaseRecycleAdapter<T> adapter, List<T> list, boolean isLoadMore, int size) {
        //判断是否加载更多
        if (isLoadMore) {
            //判断列表数据是否为空
            if (list != null && list.size() > 0) {
                //适配器设置数据
                adapter.addDatas(list);
                if (list.size() < size) {
                    //当数据少于3个时，隐藏加载更多按钮
                    binding.lineMore.setVisibility(View.VISIBLE);
                    binding.tvMore.setVisibility(View.GONE);
                } else {
                    //当数据数量正常时，默认显示加载更多按钮
                    binding.lineMore.setVisibility(View.VISIBLE);
                }
            } else {
                //当数据返回为空时，隐藏加载更多按钮
                binding.lineMore.setVisibility(View.VISIBLE);
                binding.tvMore.setVisibility(View.GONE);
            }
        } else {
            //判断列表数据是否为空
            if (list != null && list.size() > 0) {
                //当有数据时，显示加载更多按钮，隐藏缺省界面
                binding.lineMore.setVisibility(View.VISIBLE);
                if (list.size() < size) {
                    //当数据少于3个时，隐藏加载更多按钮
                    binding.tvMore.setVisibility(View.GONE);
                } else {
                    binding.tvMore.setVisibility(View.VISIBLE);
                }
                binding.emptyView.setVisibility(View.GONE);
            } else {
                //当有数据时，隐藏加载更多按钮，显示缺省界面
                binding.lineMore.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
            //适配器设置数据
            adapter.setDatas(list);
        }
    }

   //从适配器中获取前三条数据
    public <T> void loadCacheData(BaseRecycleAdapter<T> adapter) {
        List<T> data = adapter.getDatas();
        if (data != null && data.size() > viewModel.mPageSize) {
            List<T> tempList = new ArrayList<>();
            tempList.add(data.get(0));
            tempList.add(data.get(1));
            tempList.add(data.get(2));
            adapter.setDatas(tempList);
        }
    }
    //展开弹窗
    private void showPopup() {
        if (mPopWindow == null) {
            mPopWindow = new HomeGoodsSelectionTypePopWindow(getActivity());
            List<MenuEntity> menuEntities = new ArrayList<>();
            for (GoodsInfoTypeEntity3 tabEntityDatum : mTabEntityData) {
                MenuEntity entity = new MenuEntity();
                entity.setName(tabEntityDatum.getName());
                entity.setId(tabEntityDatum.getNo());
                menuEntities.add(entity);
            }
            mPopWindow.setDefItem(0);
            mPopWindow.setData(menuEntities);
            mPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    binding.ivPopup.setImageResource(R.mipmap.btn_expand2);
                    Objects.requireNonNull(binding.tabLayout.getTabAt(((int) key2))).select();
                }
            });
            mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    binding.ivPopup.setImageResource(R.mipmap.btn_expand2);
                }
            });
        }
        binding.ivPopup.setImageResource(R.mipmap.btn_expand3);
        mPopWindow.showPopwindow(binding.ivPopup, true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void checkGoodsState(String no, int pattern, CheckStateEntity stateEntity) {
        if (stateEntity.goodsIsGone()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源不存在，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {

                    })
                    .show();
        } else if (stateEntity.goodsIsReceipted()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源已被接单，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {

                    })
                    .show();

        } else {
            if (pattern == 1) {
                FreightPrjDetailActivity.start(getActivity(), no, false, false);
            } else {
                GeneralPrjDetailActivity.start(getActivity(), no, pattern, false);
            }
        }
    }
}
